package org.greyhawk.samonitor.service;


import javax.persistence.Query;

import org.greyhawk.samonitor.domain.Resources;
import org.greyhawk.samonitor.domain.ResourcesFactory;
import org.greyhawk.samonitor.domain.ResourcesType;
import org.greyhawk.samonitor.domain.Site;

public class ResourcesCrawlerRunable implements Runnable {
	
	private Site site;
	
	private ResourcesType type;
	
	private ResourcesFactory factory;
	
	private String sourcePath;
	
	private FileGenerater fileGenerater;
	
	public ResourcesCrawlerRunable(Site site,ResourcesType type,ResourcesFactory factory,String sourcePath,FileGenerater fileGenerater) {
		this.site = site;
		this.type = type;
		this.factory = factory;
		this.sourcePath = sourcePath;
		this.fileGenerater = fileGenerater;
	}
	
	public ResourcesCrawlerRunable(Site site,ResourcesType type,ResourcesFactory factory,String sourcePath) {
		this.site = site;
		this.type = type;
		this.factory = factory;
		this.sourcePath = sourcePath;
	}

	@Override
	public void run() {
		try {
			Resources resources = factory.createResources(site, type, sourcePath);
			if(!this.hasCrawler(resources.getSummary())){
				resources.persist();
				if(fileGenerater != null){
					System.out.println("==============================create file==============================");
					fileGenerater.generateFile(resources);
				}
					
			}
		} catch (Exception e) {
			e.printStackTrace();
			return;
		}
	}
	
	private boolean hasCrawler(String summary){
		Query query = Resources.findResourcesesBySummary(summary);
		int count = query.getResultList().size();
		if(count > 0)
			return true;
		else
			return false;
	}

}
